<?php

// 管理员登录
// POST manager.login

namespace app\api\resource\manager;
use think\Db;
use think\Loader;
use think\Session;

class Login
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '管理员登录';
    // 参数
    public $_param  = [
        'username' => '用户名',
        'password' => '密码',
    ];
    // 返回
    public $_return = [
        201 => '登录成功',
        422 => '请求参数不合法',
    ];

    public function run(&$request)
    {
        $params = $request->post();

        $validate = Loader::validate('Manager');
        if ( !$validate->scene('login')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $where['username'] = $params['username'];
        $where['password'] = md5($params['password']);
        $manager = Db::name('manager')->where($where)->field('password',true)->find();
        if ( is_null($manager) ) return [400,'用户名或密码错误'];
        if ( 1 == $manager['status'] ) return [400,'帐号被锁定'];

        // 写入Session
        Session::set('manager',$manager);

        return [ 201,[] ];
    }
}